use crate::app::handle::validation::send_vali_code;
use crate::app::module;
use crate::app::module::common::CommonMsg;
use crate::app::module::talker::Talker;
use crate::app::server::*;

pub const LOGIN: u16 = 11001; //登录命令
pub const REGISTR: u16 = 11002; //注册命令
pub const VALIDATION: u16 = 11003; //拉取校验码

pub struct LoginOrRegist {}

impl handle::Handle for LoginOrRegist {
    fn handle(
        &self,
        client: &mut conn::ConnEntity,
        msg: message::Message,
    ) -> (bool, message::Message) {
        let cmsg = CommonMsg::default();
        if msg.header == LOGIN {
            match login(&msg) {
                Ok(o) => {
                    let mut cmsg = cmsg.set_status(200);
                    let res = cmsg.set_data_from_struct(&o);
                    if let Err(e) = res {
                        log_error_ln!("{}", e);
                    } else {
                        match cmsg.to_message(LOGIN) {
                            Err(e) => {
                                log_error_ln!("{}", e);
                            }
                            Ok(omsg) => {
                                client.object = Box::new(o);
                                return (true, omsg);
                            }
                        }
                    }
                }
                Err(e) => match cmsg.set_status(500).set_message(&e).to_message(LOGIN) {
                    Err(e) => {
                        log_error_ln!("{}", e);
                    }
                    Ok(o) => {
                        return (true, o);
                    }
                },
            }
        } else if msg.header == REGISTR {
            let mut code = String::new();
            if let Some(s) = client.object.downcast_ref::<Talker>() {
                code = s.code.clone();
            }
            match regst(&msg, code) {
                Err(e) => {
                    log_debug_ln!("{}", e);
                    match cmsg.set_status(500).set_message(&e).to_message(REGISTR) {
                        Err(e) => {
                            log_error_ln!("{}", e);
                        }
                        Ok(o) => {
                            return (true, o);
                        }
                    }
                }
                Ok(o) => {
                    let mut cmsg = cmsg.set_status(200);
                    let res = cmsg.set_data_from_struct(&o);
                    if let Err(e) = res {
                        log_error_ln!("{}", e);
                    } else {
                        match cmsg.to_message(REGISTR) {
                            Err(e) => {
                                log_error_ln!("{}", e);
                            }
                            Ok(omsg) => {
                                return (true, omsg);
                            }
                        }
                    }
                }
            }
        } else if msg.header == VALIDATION {
            let mut talker = Talker::new();
            let ctx = msg.body.clone();
            let tomail = String::from_utf8_lossy(ctx.as_slice());
            match send_vali_code(tomail.to_string()) {
                Err(e) => {
                    match cmsg
                        .clone()
                        .set_status(500)
                        .set_message(&e)
                        .to_message(VALIDATION)
                    {
                        Err(e) => {
                            log_error_ln!("{}", e);
                        }
                        Ok(o) => {
                            return (true, o);
                        }
                    }
                }
                Ok(o) => {
                    talker.code = o;
                }
            }
            let code = talker.code.clone();
            client.object =Box::new(talker);
            let mut cmsg = cmsg.set_status(200);
            cmsg.set_data(Vec::from(code));
            match cmsg.to_message(VALIDATION) {
                Err(e) => {
                    log_error_ln!("{}", e);
                }
                Ok(o) => {
                    return (true, o);
                }
            }
        }
        (true, message::Message::new_null())
    }
}

fn login(msg: &message::Message) -> message::Result<module::talker::Talker> {
    let res: message::Result<module::talker::Talker> = msg.decode_to_json();
    let mut talker = res?;
    if talker.email == "" || talker.password == "" {
        return Err("登录邮箱和密码不能为空".to_string());
    }
    talker.find_by_email()?;
    Ok(talker)
}
fn regst(msg: &message::Message, code: String) -> message::Result<()> {
    let res: message::Result<module::talker::Talker> = msg.decode_to_json();
    let mut talker = res?;
    if talker.code != code {
        return Err(format!("code验证失败{}!={}",talker.code.clone(),code));
    }
    talker.set_iden_id();
    if talker.email == "" || talker.password == "" {
        return Err("登录邮箱和密码不能为空".to_string());
    }
    talker.insert()?;
    Ok(())
}
